﻿using System.Text.RegularExpressions;
using System;

namespace noveldown
{
    public class ClsExtension
    {

            private static readonly char[] simpleChineseNumbers = { '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' };

            private static readonly char[] unitChineseNumbers = { '十', '百', '千', '万' };

            public static int ConvertToArabic(string chineseNumber)
            {
                // 将中文数字转换为阿拉伯数字
                int result = 0;
                int digit = 0;
                int unit = 1;
                bool isDecimal = false;

                for (int i = chineseNumber.Length - 1; i >= 0; i--)
                {
                    char c = chineseNumber[i];
                    int index = Array.IndexOf(simpleChineseNumbers, c);

                    if (index >= 0)
                    {
                        digit = index;
                        if (isDecimal && unit == 1)
                        {
                            result += digit;
                        }
                        else
                        {
                            result += digit * unit;
                        }
                    }
                    else if ((index = Array.IndexOf(unitChineseNumbers, c)) >= 0)
                    {
                        unit = (index == 3 ? 10000 : (int)Math.Pow(10, index + 1));
                        isDecimal = (c == '十');
                    }
                    else if (c == '点')
                    {
                        isDecimal = true;
                    }
                }

                return result;
            }

            public static string RecognizeChineseNumbers(string text)
            {
                // 识别文本中的中文数字并转换
                return Regex.Replace(text, @"(?<chineseNumber>[\u4e00-\u9fa5]+)", m =>
                {
                    string chineseNumber = m.Groups["chineseNumber"].Value;
                    int arabicNumber = ConvertToArabic(chineseNumber);
                    return arabicNumber.ToString();
                });
            }
        
    }
}